/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.util.web;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Class to store a list of all HttpSessions and provide a means to 
 * query them.
 * 
 * @author Joe Maisel
 */
public class Sessions implements HttpSessionListener
{
	private static final List<HttpSession> sessions = new ArrayList<HttpSession>();

	/**
	 * @see com.ri.common.session.AbstractSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionCreated( HttpSessionEvent se )
	{
		sessions.add( se.getSession() );
	}

	/**
	 * @see com.ri.common.session.AbstractSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionDestroyed( HttpSessionEvent se )
	{
		sessions.remove( se.getSession() );
	}

	/**
	 * Get a list of all http sessions. The list is a copy.
	 */
	public static List<HttpSession> getAllSessions()
	{
		return new ArrayList<HttpSession>( sessions );
	}

	/**
	 * Query the list of http sessions
	 */
	public static List<HttpSession> query( SessionQuery query )
	{
		List<HttpSession> result = new ArrayList<HttpSession>();

		for( HttpSession session : sessions )
		{

			if( query.evaluate( session ) )
				result.add( session );
		}

		return result;
	}
}
